<template>
  <div>
    <div class="">
      <van-form @submit="onSubmit">
        <van-field label="编号" v-model="userForm.id" readonly></van-field>
        <van-field label="用户" v-model="userForm.name" type="text"/>

        <van-field label="原来密码" v-model="userForm.password" type="password" placeholder="请输入原密码"
                   :rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]"/>

        <van-field label="新的密码" v-model="userForm.password2" type="password" placeholder="请输入新密码"
                   :rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]"/>

        <van-field label="确认密码" v-model="userForm.password22" type="password" placeholder="请输入新密码"
                   :rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]"/>

        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>

      </van-form>
    </div>
  </div>
</template>

<script>
import * as UserAPI from "@/api/user.js";
import {
  getStorageUser
} from "@/utils/storage.js";

export default {
  data() {
    return {
      userForm: {
        id: null,
        name: "",
        password: "",
        password2: "", //新的密码
        password22: "", //确认密码
      },

      //规则:字母数字‘6~12
      regNamePwd: /^[a-z0-9]{3,12}$/i,
    };
  },
  mounted() {
    let user = getStorageUser();
    this.userForm.id = user.id;
    this.userForm.name = user.name;
  },

  methods: {

    //处理提交保存
    onSubmit() {
      if (!this.userForm.id) {
        this.$toast("用户id不能为空");
        return;
      }
      if (this.userForm.password === "") {
        this.$toast("原来密码不能为空");
        return;
      } else if (this.userForm.password2 === "") {
        this.$toast("新的密码不能为空");
        return;
      } else if (this.userForm.password2 != this.userForm.password22) {
        this.$toast("确认密码两次输入不一致");
        return;
      }

      //注意传递过去的参数的属性名
      let params = {};
      params.id = this.userForm.id;
      params.passwordOld = this.userForm.password;
      params.passwordNew = this.userForm.password2;
      UserAPI.updatePwd(params).then(() => {
        this.$toast("密码更改成功！");
        this.$router.push({
          name: "user"
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
</style>
